package com.huatai.vba.execute.handler;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.huatai.vba.common.exception.BusinessException;
import com.huatai.vba.common.utils.DateUtils;
import com.huatai.vba.dal.model.VbaFileHandler;
import com.huatai.vba.dal.model.VbaFileHandlerRecord;
import com.huatai.vba.service.VbaFileHandlerRecordService;

public abstract class ExecuteService {

	private static final Logger logger = LoggerFactory.getLogger(ExecuteService.class);

	@Autowired
	private VbaFileHandlerRecordService vbaFileHandlerRecordService;

	public void execute(VbaFileHandler handler) throws BusinessException {
		Long time1 = System.currentTimeMillis();
		VbaFileHandlerRecord record = null;
		try {
			if (StringUtils.isNotBlank(handler.getHandlerDestination()))
				handler.setHandlerDestination(DateUtils.replaceDateStr(handler.getHandlerDestination(), new Date()));
			if (StringUtils.isNotBlank(handler.getHandlerFileRegular()))
				handler.setHandlerFileRegular(DateUtils.replaceDateStr(handler.getHandlerFileRegular(), new Date()));
			if (StringUtils.isNotBlank(handler.getHandlerSource()))
				handler.setHandlerSource(DateUtils.replaceDateStr(handler.getHandlerSource(), new Date()));
			record = handler(handler);
			record.setStatus("1");
			record.setMsg("执行成功");
		} catch (Exception ex) {
			record = new VbaFileHandlerRecord();
			logger.error("执行失败", ex);
			record.setStatus("0");
			record.setFileNames("");
			record.setMsg(ex.getMessage());
		}
		record.setDestination(handler.getHandlerDestination());
		record.setSource(handler.getHandlerSource());
		Long time2 = System.currentTimeMillis();
		record.setCostTime((time2 - time1) + "");
		record.setHandlerId(handler.getHandlerId());
		vbaFileHandlerRecordService.addVbaFileHandlerRecord(record);
	}

	abstract VbaFileHandlerRecord handler(VbaFileHandler handler) throws Exception;

}
